package com.canbot.u05.activity.attendance;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.adapter.ChooseFaceAdapter;
import com.canbot.u05.bean.ChooseFaceData;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.PersonData2;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.ConstUtils;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.SystemPhotot;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 考勤选择人脸界面
 */
public class AttendanceChooseFaceActivity extends BaseActivityNoTitle implements AdapterView.OnItemClickListener {

        private static final String TAG = AttendanceChooseFaceActivity.class.getName();

        private GridView mGridView;

        private RelativeLayout remindRelativeLayout;

        private ImageView imageView;

        private ChooseFaceAdapter mCustomImageAdapter;

        private List<ChooseFaceData> mCustomAudioData;

        private Dialog dialogLoading;

        private String identification;

        private String path;

        private int lastPosition = -1;

        private   ChooseFaceData select;  //选择的


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_choose_face);
                final Intent intent = getIntent();

                identification = getIntent().getStringExtra("identification");
                mCustomAudioData = new ArrayList<>();
                initView();
        }

        @Override
        protected void onResume() {
                super.onResume();
                //加载数据
                getData();
        }

        private void initView() {

                remindRelativeLayout =  findViewById(R.id.rl_no);
                imageView = findViewById(R.id.image);
                imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                                takePhoto();
                                Intent intent = new Intent();
                                intent.setClassName("com.unisrobot.faceregcognize", "com.unisrobot.faceregcognize.activity.FaceRegRegisterActivity");
                                if (intent != null) {
                                        intent.putExtra("from","kq");
                                        intent.putExtra("ip",IpMsgConst.CHEST_SOCKET_HOST);
                                        startActivity(intent);
                                }
                        }
                });
                mGridView =  findViewById(R.id.kq_group_gridView);
                mCustomImageAdapter = new ChooseFaceAdapter(this, mCustomAudioData);
                mGridView.setAdapter(mCustomImageAdapter);
                mGridView.setOnItemClickListener(this);

        }

        private Uri imageUri;
        private static final int CAMERA_REQUEST_CODE = 1;
        private static final File parentPath = Environment.getExternalStorageDirectory();
        private static final String DST_FOLDER_NAME = "PlayCamera";
        private static String storagePath = "";
        /**
         * 拍照获取图片
         */
        public void getImageForCamera(Uri uri) {
                imageUri = uri;
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
                startActivityForResult(intent, CAMERA_REQUEST_CODE);
        }

        public void takePhoto() {
                String path = initPath();
                long dataTake = System.currentTimeMillis();
                Uri uri = Uri.fromFile(new File(path + "/" + dataTake + ".jpg"));
                getImageForCamera(uri);
        }
        /**
         * 初始化保存路径
         *
         * @return
         */
        public static String initPath() {
                if (storagePath.equals("")) {
                        storagePath = parentPath.getAbsolutePath() + "/" + DST_FOLDER_NAME;
                        File f = new File(storagePath);
                        if (!f.exists()) {
                                f.mkdir();
                        }
                }
                return storagePath;
        }

        /**
         * 拍照、图库、裁剪 回调
         */
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (resultCode != Activity.RESULT_OK) {
                        return;
                }
                switch (requestCode) {
                        case CAMERA_REQUEST_CODE:

                                if (imageUri != null) {
                                        SystemPhotot.getImage(imageUri.getPath());
//                                        Intent intent2 = new Intent(this, RegisterFaceActivity.class);
//                                        intent2.putExtra("selectedPhoto",imageUri.getPath());
//                                        startActivity(intent2);

                                        //跳转去人脸注册
                                        Intent intent = new Intent();
                                        intent.setClassName("com.unisrobot.faceregcognize", "com.unisrobot.faceregcognize.activity.RegisterFaceActivity");
                                        intent.putExtra("from","kq");
                                        intent.putExtra("selectedPhoto",imageUri.getPath());
                                        intent.putExtra("ip",IpMsgConst.CHEST_SOCKET_HOST);
                                        if (intent != null) {
                                                startActivity(intent);
                                        }
                                }
                                break;
                }
        }


        //获取某个人脸库的人脸
        private void getData() {

                remindRelativeLayout.setVisibility(View.INVISIBLE);
                //http://192.168.12.103:7755/getAudioList
                dialogLoading = LoadingDialogUtils.createLoadingDialog(AttendanceChooseFaceActivity.this, getResources().getString(R.string.attendance_load_tip));

                dialogLoading.show();
                final String url = "http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/"+ConstUtils.URL_GET_FACE_OR_GROUP;
                final HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("face", "all");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e(TAG, result);
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                                Logger.e(TAG, "onSuccess:"  + strMsgBean.toString());
                                if (strMsgBean.getRc() == 0) {
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        dialogLoading.setCancelable(true);
                                                        dialogLoading.dismiss();
                                                        mCustomAudioData.clear();
														     List<ChooseFaceData> list = new ArrayList<>();
															 
															 //hehui  add  为空判断.
															 if(strMsgBean.getResult() != null){
																  final List<PersonData2> faceList = JSON.parseArray(strMsgBean.getResult().toString(), PersonData2.class);
                                                        for (PersonData2 personData2:faceList){
                                                                ChooseFaceData chooseFaceData = new ChooseFaceData();
                                                                chooseFaceData.setIdentification(personData2.getIdentification());
                                                                chooseFaceData.setName(personData2.getName());
                                                                chooseFaceData.setGender(personData2.getSex());
                                                                chooseFaceData.setPath(personData2.getPath());
                                                                list.add(chooseFaceData);
                                                        }
															 }

                                                        if (list.size() > 0) {
                                                                mCustomAudioData.addAll(list);
                                                                if (!TextUtils.isEmpty(identification)) {
                                                                        for (int i = 0; i < mCustomAudioData.size(); i++) {
                                                                                if (identification.equals(mCustomAudioData.get(i).getIdentification())) {
                                                                                        select = new ChooseFaceData();
                                                                                        select.setIdentification(identification);
                                                                                        select.setPath(mCustomAudioData.get(i).getPath());
                                                                                        select.setChecked(true);
                                                                                        select.setGender(mCustomAudioData.get(i).getGender());
                                                                                        select.setName(mCustomAudioData.get(i).getName());
                                                                                        mCustomAudioData.get(i).setChecked(true);
                                                                                        path = mCustomAudioData.get(i).getPath();
                                                                                        lastPosition = i;
                                                                                }
                                                                        }
                                                                }

                                                                setAdapter(mCustomAudioData);
                                                                mCustomImageAdapter.notifyDataSetChanged();
                                                                remindRelativeLayout.setVisibility(View.INVISIBLE);
                                                        }
                                                        else {
                                                                //为空时，显示添加按钮 点击跳转至人脸注册页面
                                                                remindRelativeLayout.setVisibility(View.VISIBLE);
                                                        }

                                                }
                                        });
                                }
                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                dialogLoading.dismiss();
                                                ToastTools.newInstance(getApplicationContext()).showText(AttendanceChooseFaceActivity.this.getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        private void setAdapter(List<ChooseFaceData> data) {
                mCustomImageAdapter = new ChooseFaceAdapter(this, data);
                mGridView.setAdapter(mCustomImageAdapter);
        }

        /*确认*/
        public void nextStep(View view) {

                if (select == null) {
                        ToastTools.newInstance(this).showText("请选择人脸信息");
                        return;
                }
                identification = select.getIdentification();
                path = select.getPath();
                final Intent intent = new Intent();
                intent.putExtra("identification", identification);
                intent.putExtra("path", path);
                intent.putExtra("isChecked", true);
                setResult(Activity.RESULT_OK, intent);
                finish();
        }

        /*返回*/
        public void back(View view) {
                setResult(RESULT_CANCELED);
                finish();
        }


        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mCustomAudioData.get(position).isChecked()) {
                        mCustomAudioData.get(position).setChecked(false);
                        mCustomImageAdapter.updateView(position, mGridView);
                        select = null;
                }
                else {
                        mCustomAudioData.get(position).setChecked(true);
                        mCustomImageAdapter.updateView(position, mGridView);
                        select = mCustomAudioData.get(position);
                }
                if (lastPosition != -1
                        && mCustomAudioData.get(lastPosition).isChecked()
                        && lastPosition != position) {
                        mCustomAudioData.get(lastPosition).setChecked(false);
                        mCustomImageAdapter.updateView(lastPosition, mGridView);
                }
                lastPosition = position;
                Logger.e("ShoppingChooseAudioActi", "音频预览" + mCustomAudioData.get(position).getPath());
        }
}
